#include <iostream>
#include <string>
using namespace std;
  void reverse_again(string &s,size_t begin,size_t find){
        if(begin >= find){
            return;
        }
        size_t lh = begin, rh = find;
        while(lh < rh){
           swap(s[lh++], s[rh--]);
       }
       return;
    }  
    void reverseWords(string &s) {
        if(s.length()==0){
            return;
        }
        size_t find = s.find_first_of(" ");
		size_t begin = s.find_first_not_of(" ");
		size_t end = s.find_last_not_of(" ");
		if(find == string::npos){
			return;
		}
		if(begin != string::npos && end != string::npos){
			s = s.substr(begin, end-begin+1);
		}else{
			s = "";
			return;
		}
       while(begin < end){
           swap(s[begin++], s[end--]);
       }
       find = s.find_first_of(" ");
       begin = s.find_first_not_of(" ");
       while(find != string::npos && begin != string::npos){
			if(find >= begin){
		       reverse_again(s, begin, find-1);
			}
		   if(find == s.length()-1){
				break;
			}
           begin = s.find_first_not_of(" ", find+1);
           find = s.find_first_of(" ", find+1);
       }
		if(s.find_last_of(" ") != string::npos && s.find_last_not_of(" ") != string::npos){
       		reverse_again(s, s.find_last_of(" ")+1, s.find_last_not_of(" "));
		}
       return;
    }
   

int main(){
	string s = "hello world!";
	reverseWords(s);
	cout<<s<<endl;
	return 0;
}

